﻿using System.Runtime.InteropServices;

namespace System
{
    public class BytesTools
    {
        public static byte[] StructToBytes(object structObj, int size = 0)
        {
            if (size == 0)
            {

                size = Marshal.SizeOf(structObj); //得到结构体大小
            }
            IntPtr buffer = Marshal.AllocHGlobal(size);  //开辟内存空间
            try
            {
                Marshal.StructureToPtr(structObj, buffer, false);   //填充内存空间
                byte[] bytes = new byte[size];
                Marshal.Copy(buffer, bytes, 0, size);   //填充数组
                return bytes;
            }
            catch (Exception ex)
            {
                Console.WriteLine("struct to bytes error:" + ex);
                return null;
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);   //释放内存
            }
        }

        public static object BytesToStruct(byte[] bytes, Type strcutType, int nSize,int StartIndex)
        {
            if (bytes == null)
            {
                Console.WriteLine("null bytes!!!!!!!!!!!!!");
            }
            //int size = Marshal.SizeOf(strcutType);
            IntPtr buffer = Marshal.AllocHGlobal(nSize);
            try
            {
                Marshal.Copy(bytes, StartIndex, buffer, nSize);
                return Marshal.PtrToStructure(buffer, strcutType);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Type: " + strcutType.ToString() + "---TypeSize:" + Marshal.SizeOf(strcutType) + "----packetSize:" + nSize+"---error:"+ex.Message);
                return null;
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);
            }
        }

        /// <summary>
        /// 转换为相应结构体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="bytes"></param>
        /// <param name="nSize"></param>
        /// <returns></returns>
        public static T BytesTo<T>(byte[] bytes, int StartIndex = 0,int nSize = 0)
        {
            
            if (nSize <= 0) { nSize = Marshal.SizeOf(typeof(T)); }
            return (T)BytesToStruct(bytes, typeof(T), nSize,StartIndex);
        }

    }
}
